package cn.hughie.sort;

import utils.SortUtils;

import java.util.Arrays;

/**
 * 归并排序
 *
 * @author yuh
 * @date 2018/5/15 12:35
 */
public class MergeSort {

    private static Comparable[] aux;

    /**
     * 排序入口
     *
     * @param arr
     */
    public static void sort(Comparable[] arr) {
        aux = new Comparable[arr.length];
        mergeSort(arr, 0, arr.length - 1);
    }

    /**
     * 归并排序
     *
     * @param arr
     * @param l
     * @param r
     */
    public static void mergeSort(Comparable[] arr, int l, int r) {
        if (l >= r) {
            return;
        }
        int mid = (l + r) / 2;
        mergeSort(arr, l, mid);
        mergeSort(arr, mid + 1, r);
        merge(arr, l, r, mid);
    }

    /**
     * 归并
     *
     * @param arr
     * @param l
     * @param r
     * @param mid
     */
    public static void merge(Comparable[] arr, int l, int r, int mid) {
        System.arraycopy(arr, 0, aux, 0, arr.length);
        int i = l;
        int j = mid + 1;
        for (int k = l; k <= r; k++) {
            if (i > mid) {
                arr[k] = aux[j++];
            } else if (j > r) {
                arr[k] = aux[i++];
            } else if (SortUtils.largerThan(aux[i], aux[j])) {
                arr[k] = aux[j++];
            } else {
                arr[k] = aux[i++];
            }
        }
    }

    public static void main(String[] args) {
        Integer[] arr = {2, 3, 4, 1, 3, 4, 52, 44, 41, 41, 41, 41, 4, 14, 141, 41, 14, 1, 41, 41, 4, 14};
        sort(arr);
        SortUtils.isSorted(arr);
    }

}
